package cn.groupmarket.domain.trade.service.filter;

import cn.groupmarket.domain.trade.adapter.repository.ITradeOrderRepository;
import cn.groupmarket.domain.trade.model.entity.GroupBuyActivityEntity;
import cn.groupmarket.domain.trade.model.entity.TradeRuleCommandEntity;
import cn.groupmarket.domain.trade.model.entity.TradeRuleFilterBackEntity;
import cn.groupmarket.domain.trade.service.factory.TradeRuleFilterFactory;
import cn.groupmarket.types.design.framework.link.model2.handler.ILogicHandler;
import cn.groupmarket.types.enums.ResponseCode;
import cn.groupmarket.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class UserTakeLimitRuleFilter implements ILogicHandler<TradeRuleCommandEntity, TradeRuleFilterFactory.DynamicContext, TradeRuleFilterBackEntity> {
    @Resource
    private ITradeOrderRepository tradeOrderRepository;

    @Override
    public TradeRuleFilterBackEntity apply(TradeRuleCommandEntity requestParameter, TradeRuleFilterFactory.DynamicContext dynamicContext) throws Exception {
        log.info("交易规则过滤-用户参与次数校验{},activityId{}",requestParameter.getUserId(),requestParameter.getActivityId());
        GroupBuyActivityEntity groupBuyActivity = dynamicContext.getGroupBuyActivityEntity();
        Integer count = tradeOrderRepository.queryOrderCountByActivityId(requestParameter.getActivityId(),requestParameter.getUserId());
        if(groupBuyActivity.getTakeLimitCount() != null && count >= groupBuyActivity.getTakeLimitCount()  ){
            throw new AppException(ResponseCode.E0103);
        }
        return TradeRuleFilterBackEntity.builder()
                .userTakeOrderCount(count)
                .build();
    }
}
